package com.aaa.service.systemmanage.impl;

import com.aaa.dao.systemmanage.MenuDao;
import com.aaa.entity.MenuTree;
import com.aaa.entity.systemmanage.Menu;
import com.aaa.service.systemmanage.MenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("menuService")
public class MenuServiceImpl implements MenuService {

    @Resource
    private MenuDao menuDao;

    //查询所有
    @Override
    public List<Menu> queryAll() {
        List<Menu> menus = menuDao.quertyAll();
        return menus;
    }

    //查询所有名字
    @Override
    public Map<String, Object> queryMenuByUsername(String username) {
        Map<String, Object> map = new HashMap();

        List<Menu> menuList = menuDao.queryMenuByUsername(username);
        List<Menu> firstMenuList = new ArrayList<>();
        List<Menu> secondMenuList = new ArrayList<>();
        //菜单分类
        for (Menu menu : menuList) {
            if (menu.getMenuType().equals("M")) {
                //一级菜单
                firstMenuList.add(menu);
            }
            if (menu.getMenuType().equals("C")) {
                //二级菜单
                secondMenuList.add(menu);
            }
        }
        map.put("firstMenuList", firstMenuList);
        map.put("secondMenuList", secondMenuList);
        return map;
    }

    //查询所有到下拉框
    @Override
    public List<MenuTree> queryAllToSelect() {
        List<Menu> menus = menuDao.queryAllToSelect();
        List<MenuTree> list = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParentId() == 0) {
                MenuTree menuTree = new MenuTree();
                menuTree.setId(menu.getMenuId());
                menuTree.setTitle(menu.getMenuName());
                menuTree.setChildren(getChildrenMenu(menu.getMenuId(), menus));
                list.add(menuTree);
            }
        }
        return list;
    }

    //查询到下拉框
    @Override
    public List<Integer> querySelect(int roleId) {
        return menuDao.findSelectMenu(roleId);
    }

    //修改
    @Override
    public boolean update(Menu menu) {
        return menuDao.update(menu);
    }


    //递归查询子部门
    public List<MenuTree> getChildrenMenu(Integer parentId, List<Menu> menus) {
        List<MenuTree> list = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParentId().equals(parentId)) {
                MenuTree menuTree = new MenuTree();
                menuTree.setId(menu.getMenuId());
                menuTree.setTitle(menu.getMenuName());
                menuTree.setChildren(getChildrenMenu(menu.getMenuId(), menus));
                list.add(menuTree);
            }
        }
        return list;
    }


}
